// SceneManager.ts
import { _decorator, director, Scene } from 'cc';

export class SceneManager {
    private static _inst: SceneManager;
    private _sceneData: Record<string, any> = {};

    public static get inst(): SceneManager {
        if (!this._inst) {
            this._inst = new SceneManager();
        }
        
        return this._inst;
    }

    // 存储场景参数
    public setSceneData(sceneName: string, data: any) {
        this._sceneData[sceneName] = data;
    }

    // 获取场景参数
    public getSceneData(sceneName: string): any {
        return this._sceneData[sceneName];
    }

    // 标准加载场景（支持 data + onLaunched）
    public loadScene(
        sceneName: string,
        data?: any,
        onLaunched?: (error: Error | null, scene?: Scene) => void
    ) {
        if (data) {
            this.setSceneData(sceneName, data);
        }
        director.loadScene(sceneName, onLaunched);
    }

    // 支持 options 参数（如 delay）
    public loadSceneWithOptions(
        sceneName: string,
        data?: any,
        options?: {
            onLaunched?: (error: Error | null, scene?: Scene) => void;
            delay?: number;
        }
    ) {
        if (data) {
            this.setSceneData(sceneName, data);
        }
        director.loadScene(sceneName, options?.onLaunched);
    }

    // Promise 方式加载
    public async loadSceneAsync(
        sceneName: string,
        data?: any,
        options?: { delay?: number }
    ): Promise<Scene | null> {
        if (data) {
            this.setSceneData(sceneName, data);
        }
        return new Promise((resolve, reject) => {
            director.loadScene(sceneName, (error, scene) => {
                if (error) {
                    reject(error);
                } else {
                    resolve(scene);
                }
            });
        });
    }
}